package com.tim.arc.groovy;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;

public class ScriptExecute {

    public static void main(String[] args) throws Exception {
        executeHello();

    }

    public static void executeHello() throws IOException {
        String path="D:\\project\\autil\\autil\\src\\main\\java\\com\\tim\\arc\\groovy\\HelloWorld.groovy";
        String name="hello";
        Object args=null;
        Object result = execute(path, name, args);
        System.out.println(result);
    }

    public static Object execute(String path, String name, Object args) throws IOException {
        String content = Files.readAllLines(Paths.get(path)).stream().collect(Collectors.joining("\n"));
        //创建GroovyShell
        Binding binding=new Binding();
        GroovyShell groovyShell = new GroovyShell(binding);
        binding.setProperty("","");//不用
        binding.setVariable("a","b");//推荐
        //装载解析脚本代码
        Script script = groovyShell.parse(content);
        //执行
        return script.invokeMethod(name, args);

    }
}
